<!-- http://www.imooc.com/wiki/uniapp/databinding.html -->
<template>
	<view>
		<!-- 标题 -->
		<view class="page-title" @click="showName">
			<view class="page-title__wrapper">
				<text class="page-title__text">{{title}}</text>
			</view>
		</view>
		
		<intervalBar></intervalBar>
		
		<!-- <bdinput :dc='phone_number' @retMsg='getMsg' v-if="forceReset"></bdinput> -->
		<!-- <bdinput :dc='verify_code_dc' @retMsg='getMsg' v-if="forceReset"></bdinput> -->
		<bdphonecode :phone_number_dc='phone_number' 
		:verify_code_dc='verify_code_dc'
		@retMsg='getMsg'
		@clickedverifyCodeButton='clickedverifyCodeButton'
		>
			
		</bdphonecode>
		
		<!-- 测试 -->
		<!-- <bdinput :dc='name' @retMsg='getMsg'></bdinput> -->
		
		<intervalBar></intervalBar>
		
		<!-- 姓名 -->
		<bdinput :dc='name' @retMsg='getMsg' v-if="forceReset" v-model='user_info.name'></bdinput>
		
		<!-- 选择性别 -->
		<bdpicker :dc='sex' @retMsg='getPickerMsg' v-if="forceReset"></bdpicker>
		<!-- 选择专业 -->
		<bdpicker ref="child" v-if="hackReset" :dc='selected_major' @retMsg='getPickerMsg'></bdpicker>
		<!-- 学校 -->
		<bdinput :dc='current_school' @retMsg='getMsg' v-if="forceReset"></bdinput>
		
		<bdinput :dc='current_class' @retMsg='getMsg' v-if="forceReset"></bdinput>
		
		<intervalBar></intervalBar>
		
		<!-- 省市区选择器 -->
		<view class="picker_view">
			<!-- 文本 -->
			<view class='picker_text'>
				<text>{{"地址选择"}}</text>
			</view>
			<view class="picker"  @click="addressShow = true" >
				<view class="picker_input">
					<input maxlength="20"
					:placeholder="address?address:'点击选择地址'"
					 disabled="true"
					 />
				</view>
				<uni-icons class="icons" type="arrowright" size="20"/>
			</view>
		    <view class="picker_address">
		        <pickerAddress v-model="addressShow" @confirm="addresspick" />
		    </view>
		</view>
		<!-- 详细地址 -->
		<bdinput :dc='address_detail' @retMsg='getMsg' v-if="forceReset"></bdinput>
		
		<intervalBar></intervalBar>
		
		<!-- 图片选择 -->
		<view class='images_container'>
			<!-- test_image  stype="z-index: 2"  -->
			<view style="position: relative;" v-for="(item, index) in [user_info.picture_sign, user_info.picture_id_card_positive]" :key="index">
				<image @click="preview(img_list[index])"
				 :src="item"></image>
				<image class="shancs" src="./shanchus2.png" mode="" @click="selec(index)"></image>
			</view>
			
			<view v-if="user_info.picture_sign">
				<view class='show_img_container'>
					<image class="shancs" src="./shanchus2.png" mode="" @click="selec('0')"></image>
					<image class='show_img' @click="preview(user_info.picture_sign)"
					 :src="user_info.picture_sign"></image>
				</view>
			</view>
			<view v-else>
				<uni-file-picker
				class='img'
				ref="files" 
				:auto-upload="false"  
				
				v-model="img_ls"
				@select="picture_sign" 
				:image-styles="imageStyles"
				:limit="1"
				>
				电子签名照片
				</uni-file-picker>
			</view>
			
			<uni-file-picker 
			class='img'
			ref="files" 
			:auto-upload="false"  
			@select="picture_id_card_positive" 
			:image-styles="imageStyles"
			:limit="1"
			>
				<view v-if="user_info.picture_id_card_positive" >
					<!-- <image @click="preview(user_info.picture_id_card_positive)"
					 :src="user_info.picture_id_card_positive"></image> -->
					<image :src="user_info.picture_id_card_positive">
				</view>
				<view v-else>
					身份证正面照<br>(国徽面)
				</view>
			</uni-file-picker>
			
			<uni-file-picker
			class='img'
			ref="files" 
			:auto-upload="false"  
			@select="picture_id_card_negative" 
			:image-styles="imageStyles"
			:limit="1"
			>
				<view v-if="user_info.picture_id_card_positive">
					<img :src="user_info.picture_id_card_negative">
				</view>
				<view v-else>
					身份证反面照<br>(人像面)
				</view>
			</uni-file-picker>
			
			<view v-if="user_info.picture_id_card_negative">
				
			</view>
			<view v-else>
			</view>
			
			
		</view>
		
		<intervalBar></intervalBar>
		
		<button class='submit_button' @click="showData">提交数据</button>
	</view>
</template>


<script>
	import ttt from "components/bdpicker/ttt.vue"
	import bdpicker from "components/bdpicker/bdpicker.vue"
	import bdinput from "components/bdpicker/bdinput.vue"
	import bdphonecode from "../../components/bdpicker/bdphonecode.vue"
	import myPicker from "components/bdpicker/myPicker.vue"
	import intervalBar from "../../components/bdpicker/intervalBar.vue"
	import pickerAddress from '@/components/liudx-pickerAddress/index.vue'
	export default {
		//注册组件
		components: {
		  intervalBar,
		  bdpicker,
		  bdinput,
		  pickerAddress,
		  bdphonecode,
		  ttt,
		  myPicker
		},
		data () {
			return {
				imageStyles:{
					width: 128,
					height: 128,
					// border:{
					// 	color:"#ff5a5f",
					// 	width:2,
					// 	style:'dashed',
					// 	radius:'2px'
					// },
					// margin-left: 20,
					// padding: 20,
				},
				title: '预报名申请表',
				imageValue:[],
				// 用于提交的user信息
				user_info: {
					id: null,
					name: '1111',
					phone_number: null,
					selected_major: '',
					sex: '',
					province: '',
					city: '',
					area: '',
					current_school: '',
					current_class: '',
					address_detail: '',
					address_selected: '',
					
					picture_id_card_positive: null,
					picture_id_card_negative: null,
					picture_sign: null,
				},
				
				// 前端界面信息
				current_class: {
					text: '班级',
					placeholder: '所在班级',
					value: '',
				},
				current_school: {
					text: '学校',
					placeholder: '所在学校',
					value: '',
				},
				address_detail: {
					text: '详细地址',
					placeholder: '请输入您的详细地址',
					value: '',
				},
				phone_number: {
					text: '手机号',
					placeholder: '请输入您的手机号',
					type: "number",
					value: '',
				},
				verify_code_dc: {
					text: '验证码',
					placeholder: '短信验证码',
					// type: "number",
					value: '',
				},
				name: {
					text: '姓名',
					placeholder: '请输入您的姓名',
					value: '',
				},
				
				// bdpiker
				sex: {
					text: '所选性别',
					placeholder: '请选择您的性别',
					names: ['男', '女'],
					value: '',
				},
				
				// 省市区
				addressShow: false,
				form: {
					// 默认内蒙古
				    province: "150000",
				    city: "150100",
				    area: "1501219f2a",
				},
				address: '',
				
				// ------- 专业选择
				selected_major: {
					text: '所选专业',
					placeholder: '请选择专业',
					// names: ['计算机', '挖掘机', '会计'],
					names: ['1', '2'],
					value: '',
					// add_placeholder_to_names: true,
				},
				major_list: [],
				hackReset: true,
				forceReset: true,		// v-if="forceReset"
				
				currentValue: '123',
				options: ["广东","上海","北京","深圳"],
				
				img_ls: [],
			}
		},
		onLoad(){
			this.init();
			this.getMajors();
		},
		methods: {
			setValue(key, value){
				this[key].value = value;
				this.user_info[key] = value;
			},
			init(){
				// uni.clearStorage();		// 清除缓存
				// 加载缓存
				var value = uni.getStorageSync('phone_number');
				
				// 初始化一些值, 便于测试
				this.setValue('phone_number', (value));
				this.setValue('verify_code_dc', 'ttod123');
				
				// this.phone_number.value = 18510779120;
				// this.user_info.phone_number = 18510779120;
				// this.verify_code_dc.value = 'ttod123';
			},
			
			//删除 test_image
			selec(index) {
				var dc = {
					0: 'picture_sign',
					1: 'picture_id_card_positive',
					2: 'picture_id_card_negative'
				};
				this.user_info[dc[index]] = null;
				// this.img_list.splice(index, 1)
				// this.$emit('obtain_img', this.img_list)
			},
			clickedverifyCodeButton(user_info) {
				console.log('~~~~~~~ id, user_info: ', this.user_info.id, ' - ', user_info);
				if ( user_info ){
					console.log('~~~ 验证成功, 加载用户信息中...');
					this.getUserSubmitedInfo();
					
					return uni.showToast({
						title: '验证通过, 加载数据中...',
						icon: 'none',
						position: 'center'
					});
				}
			},
			preview(urls) {
				// console.log(index)
				console.log('=== ', urls, this.$isArrayFn([urls]));
				var index = 0;
				
				
				console.log('~~~~~~~~~~~')
				uni.previewImage({
					urls: [urls],
					current: index,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			getImgLs(){
				this.img_ls = [this.user_info.picture_sign];
				console.log('~~ img_ls: ', this.img_ls);
			},
			
			async getUserSubmitedInfo(){
				console.log('--- 尝试获取用户已经提交的信息 ---');
				var myData =  {
						'phone_number': this.user_info.phone_number,
						'order_type_ls': ['-id', ],
				};
				if(! myData['phone_number']){
					console.log('myData的phone_number为空, 不能查询用户信息!');
					return 1;
				}
				
				// console.log('userinfophonenumber', user_info.phone_number);
				// 设置缓存
				uni.setStorageSync('phone_number', this.user_info.phone_number);
				
				// 加载缓存
				// var value = uni.getStorageSync('phone_number');
				// console.log('====== getStorageSync_value', value, user_info);
				
				
				const res = await this.$myGetFunction({
					url: '/api/index/ForecastRegistration/',
					data: myData,
				})
				console.log('*** myData', myData)
				console.log('***** res: ', res);
				
				var result = res.data.result;
				if (result.data.length == 0){
					console.log('--- 未找到用户信息! 应该是第一次报名.')
					return 1
				}
				
				var resp_user_info = result.data[0];
				
				// 开始赋值
				let data_dc = this._data
				for(var k in resp_user_info){
					var v = resp_user_info[k];
					
					if (data_dc[k]){
						data_dc[k].value = resp_user_info[k];
					}
					data_dc.user_info[k] = resp_user_info[k];
				}
				this.address = resp_user_info['address_selected'];
				
				console.log(resp_user_info)
				console.log(data_dc)
				// this.getImgLs();
			},
			getMajors() {
				uni.request({
					method: 'GET',
				    url: this.$baseUrl + '/api/myconf/Major/',
					success: (res) => {
						var data = res.data.result.data;
						
						this.selected_major.names = []
						this.major_list = []
						for(var i = 0; i < data.length; i++){
							var d = data[i]['name'];
							this.selected_major.names.push(d);
						}
						
						// --- (已通过v-model解决)重新加载子组件的两种方案, hackReset: 强制重载, $refs: 直接修改子组件的数据
						// this.hackReset = false;
						// this.$nextTick(() => {
						//    this.hackReset = true;
						// })
						// this.$refs.child.names = this.selected_major.names;    // 这句很重要
					}
				});
				
			},
			picture_sign(e){
				var filePath0 = e.tempFilePaths[0];
				this.user_info.picture_sign = filePath0;
				console.log('选择文件picture_sign：', filePath0);
			},
			picture_id_card_positive(e){
				var filePath0 = e.tempFilePaths[0];
				this.user_info.picture_id_card_positive = filePath0;
				console.log('选择文件picture_id_card_positive：', filePath0);
			},
			picture_id_card_negative(e){
				var filePath0 = e.tempFilePaths[0];
				this.user_info.picture_id_card_negative = filePath0;
				console.log('选择文件picture_id_card_negative：', filePath0);
			},
			addresspick(obj) {
				let arr = [ 'province', 'city', 'area'];
				let place = '';

				arr.map(key => {
					this.form[key] = obj[key].AreaId
					place += obj[key].AreaName + "/"
				})
				place = place.substring(0, place.length - 1);
				this.address = place;
				
				this.user_info.address_selected = place;
				this.user_info.province = obj['province'].AreaName
				this.user_info.city = obj['city'].AreaName
				this.user_info.area = obj['area'].AreaName
			},
			getPickerMsg(res){
				// 仅适用于bdpicker, 将value赋值到对应的组件dc中.
				let data_dc = this._data
				for(var k in data_dc){
					var v = data_dc[k];
					if (v['text'] == res.dc['text'] && v['placeholder'] == res.dc['placeholder']){
						v.value = res.value;
						// 赋予user_info
						data_dc.user_info[k] = v.value;
					}
				}
			},
			getMsg(res){
				// 仅适用于bdinput, 将value赋值到对应的组件dc中.
				let data_dc = this._data
				for(var k in data_dc){
					var v = data_dc[k];
					
					if (v['text'] == res.dc['text'] && v['placeholder'] == res.dc['placeholder']){
						v.value = res.value;
						// 赋予user_info
						data_dc.user_info[k] = v.value;
					}
				}
			},
			
			//*上传图片*//
			async uploadimage() {
				console.log('---------- 开始上传图片 ------')
				var myUrl = this.newUrl;
				// var myUrl = this.$baseUrl + '/api/index/ForecastRegistration/99/';
				const name_ls = ['picture_sign', 'picture_id_card_positive', 'picture_id_card_negative'];
				
				var i = -1;
				var field_name = "";
				var img_path = "";
				// 上传已保存的照片
				// const tempFilePaths = this.imglist;
				console.log('~~~ myUrl:', myUrl);
				
				i += 1;
				field_name = name_ls[i];
				img_path = this.user_info[field_name]
				console.log('~~~~~~~~~~~~~~ i field_name:', i, field_name);
				console.log('--- img_path ', img_path)
				
				// 第一张图片 picture_sign
				await uni.uploadFile({
				    url: myUrl,
				    filePath: img_path,
				    name: field_name,
				    formData: {
						'post_type': 'update'
				    },
				    success: (uploadFileRes) => {
						var data = JSON.parse(uploadFileRes.data);
						if(200 <= data.status < 300){
							console.log(i, '*** Update Successfully!', field_name);
						}
						console.log(i, '--- data: ', data);
						
						i += 1;
						field_name = name_ls[i];
						img_path = this.user_info[field_name]
						console.log('~~~~~~~~~~~~~~ i field_name:', i, field_name);
						console.log('--- img_path ', img_path)
						
						// 第二张图片 picture_id_card_positive'
						uni.uploadFile({
						    url: myUrl,
						    filePath: img_path,
						    name: field_name,
						    formData: {
								'post_type': 'update'
						    },
							success: (uploadFileRes) => {
								var data = JSON.parse(uploadFileRes.data);
								if(200 <= data.status < 300){
									console.log(i, '*** Update Successfully!', field_name);
								}
								console.log(i, '--- data: ', data);
								
								i += 1;
								field_name = name_ls[i];
								img_path = this.user_info[field_name]
								console.log('~~~~~~~~~~~~~~ i field_name:', i, field_name);
								console.log('--- img_path ', img_path)
								
								// 第三张图片 picture_id_card_negative
								uni.uploadFile({
								    url: myUrl,
								    filePath: img_path,
								    name: field_name,
								    formData: {
										'post_type': 'update'
								    },
									success: (uploadFileRes) => {
										var data = JSON.parse(uploadFileRes.data);
										if(200 <= data.status < 300){
											console.log(i, '*** Update Successfully!', field_name);
										}
										console.log(i, '--- data: ', data);
										
										return uni.showToast({
											title: '图片上传成功!',
											icon: 'none',
											position: 'center'
										});
									},
								})
							},
						})
				    }
				});
				
			},
			
			async submitBaseInfo() {
				console.log('--- 上传基本信息 ---');
				var myUrl = this.$baseUrl + '/api/index/ForecastRegistration/';
				var method = 'POST'
				
				var url_1 = myUrl;		// 根据不同用户, 可能会由post变成put
				console.log('~~~ method, myurl:', method, '-', myUrl);
				
				// var data = this.user_info;
				var data = JSON.parse(JSON.stringify(this.user_info));
				data.picture_id_card_negative = null;
				data.picture_id_card_positive = null;
				data.picture_sign = null;
				
				if (this.user_info.id != undefined){
					url_1 += this.user_info.id.toString() + '/';
					data.post_type = 'update'
				}
				
				await uni.request({
					method: method,
					url: url_1,
					data: data,
					success: (res) => {
						console.log('--- res.data: ', res.data);
						var result = res.data.result;
						var newUrl = myUrl + result.id.toString() + '/';
						
						console.log('--- newUrl: ', newUrl);
						this.newUrl = newUrl;
						
						// 这里出bug了, xxx is not a function. 这是因为res要用指针=>, 不能直接=等于.
						// this.picture_sign("a");
						this.uploadimage();
					},
					fail(err) {
						uni.showToast({
							title: '获取数据失败',
							icon: 'none',
						})
					}
				})
				
			},
			showName(){
				console.log('user_info: ', this.$data.user_info);
				console.log('data: ', this.$data);
			},
			showData() {
				// let data_dc = this._data
				// for(var k in data_dc){
				// 	var v = data_dc[k];
				// 	console.log('~~~ ', k, ' - ',  v);
				// }
				this.submitBaseInfo();
				// this.uploadimage();
			},
			
		}
	}
</script>


<style lang="scss" scoped>
	
	// 标题
	.page-title{
		font-weight:bold;
		font-size: 48upx;
		text-align:center;
		// margin-bottom: 40upx;
	}
	.submit_button{
		background-color: #3729ff;
		color: #fff;
	}
	
	// 间隔栏
	.interval_bar{
		height: 20rpx;
		background-color: #F4F5F6;
	}
	
	// 地址选择框视图
	.picker_view {
		width: 100%;
		display: flex;
		border-top: 3upx solid #ccc;
		border-bottom: 3upx solid #ccc;
		padding: 20upx;
	}
	.picker_text {
		width: 25%;
	}
	
	// 地址选择框
	.picker {
		width: 65%;
		float: right;
		display: block;
	}
	.picker_input {
		width: 80%;
		float: left;
		text-align: right;
		margin-right: 10upx;
		// margin-left: 40upx;
	}
	.picker_icons {
		float: right;
		width: 20%;
	}
	
	// 图片容器
	.images_container {
		display: flex;
	}
	.img {
		margin-left: 10upx;
		margin-right: 10upx;
		color: #303133;
	}
	
	// 展示图片的容器
	.show_img_container {
		position: relative;
	}
	.show_img {
		width: 180upx;
		height: 180upx;
		margin-left: 10upx;
		margin-right: 10upx;
		color: #303133;
		position: relative;
	}
	
	// 删除图标 test_image
	.shancs {
		width: 10vw;
		height: 10vw;
		color: #eee;
		position: absolute;
		top: -10upx;
		right: -10upx;
		z-index: 1;
	}
</style>
